<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 * user log api
 * TODO 减少小于0时 在memberAPI 和 memberexpapi 中判断
 * TODO 代码重构
 */
namespace app\system\api;
use app\common\api\BaseApi;
use app\system\model\UserLog;

class UserLogApi extends BaseApi{
	protected $return = [];
	const QUERY_NO_PAGING = "system/UserLogApi/queryNoPaging";
	const ADD             = "system/UserLogApi/add";
	const SAVE            = "system/UserLogApi/save";
	const GET_INFO        = "system/UserLogApi/getInfo";
	const SAVE_BY_ID      = "system/UserLogApi/saveByID";
	const DELETE          = "system/UserLogApi/delete";
	const QUERY           = "system/UserLogApi/query";

	/*奖励*/
	const THREAD_ADD      = "system/UserLogApi/threadAdd";
	const THREAD_DELETE   = "system/UserLogApi/threadDel";
	const FIRST_AVATAR    = "system/UserLogApi/firstAvatar";
	const FIRST_ADDRESS   = "system/UserLogApi/firstAddress";
	const REGISTER        = "system/UserLogApi/register";
	const POST_ME         = "system/UserLogApi/postTo";
	const POST_ADD        = "system/UserLogApi/postAdd";
	const POST_DELETE     = "system/UserLogApi/postDel";

	protected function _init(){
		$this->model  = new UserLog();
		$this->return = ['err'=>[],'suc'=>[]];
	}

	//删除回帖
	public function postDel($uid){
		return $this->addAndLog($uid,UserLog::POST_DELETE);
	}

	private function getWhereToday($field,$strDate = false){
		if($strDate) $start = strtotime(date($strDate));
		else $start = strtotime(date('Y-m-d',time()));
		$end   = $start + 3600*24;
		return $field.' between '.$start.' and '.$end;
	}
	//获取今天此类积分总额
	private function getDailyScore($uid,$type){
		$r = apiCall(UserLogApi::QUERY_NO_PAGING,[['num_type'=>0,'op_type'=>$type,'uid'=>$uid,'_string'=>$this->getWhereToday('time')],false,'number']);
			if(!$r['status']) return $this->apiReturnErr($r['info']);
			$daily_score = 0;
			foreach ($r['info'] as $v) {
				$daily_score += intval($v['number']);
		}
		return $this->apiReturnSuc($daily_score);
	}
	//收到回帖
	public function postTo($uid){
		//检查今天收到回帖积分
		$str 	   = UserLog::POST_ME;
		$typearr = explode(',',$str);
		$type    = $typearr[0];
		$score   = intval($typearr[1]);
		$r = getCacheTree('SCORE_GET_THREAD_POST',3);
		if(!$r['status']) return $this->apiReturnErr($r['info']);
		$max_daily = intval($r['info']);
		if($max_daily>0){
			//获取今天此类积分总额
			$r = $this->getDailyScore($uid,$type);
			if(!$r['status']) return $this->apiReturnErr($r['info']);
			$daily_score = $r['info'];
			if($max_daily < $daily_score + $score) return $this->apiReturnSuc(['err'=>[],'suc'=>[UserLog::SCORE.'上限']]);
		}
		return $this->addAndLog($uid,$str);
	}
	//回帖
	public function postAdd($uid){
		//检查今天回帖积分
		$str     = UserLog::POST_ADD;
		$typearr = explode(',',$str);
		$type    = $typearr[0];
		$score   = intval($typearr[1]);
		$r = getCacheTree('SCORE_THREAD_POST',3);
		if(!$r['status']) return $this->apiReturnErr($r['info']);
		$max_daily = intval($r['info']);
		if($max_daily>0){
			//获取今天此类积分总额
			$r = $this->getDailyScore($uid,$type);
			if(!$r['status']) return $this->apiReturnErr($r['info']);
			$daily_score = $r['info'];
			if($max_daily < $daily_score + $score) return $this->apiReturnSuc(['err'=>[],'suc'=>[UserLog::SCORE.'上限']]);
		}
		return $this->addAndLog($uid,UserLog::POST_ADD);
	}
	//发帖
	public function threadAdd($uid){
		//检查今天奖励上限
		$str     = UserLog::THREAD_ADD;
		$typearr = explode(',',$str);
		$type    = $typearr[0];
		$score   = intval($typearr[1]);
		$r = getCacheTree('SCORE_THREAD_ADD',3);
		if(!$r['status']) return $this->apiReturnErr($r['info']);
		$max_daily = intval($r['info']);
		if($max_daily>0){
			//获取今天此类积分总额
			$r = $this->getDailyScore($uid,$type);
			if(!$r['status']) return $this->apiReturnErr($r['info']);
			$daily_score = $r['info'];
			if($max_daily < $daily_score + $score) return $this->apiReturnSuc(['err'=>[],'suc'=>[UserLog::SCORE.'上限']]);
		}
		return $this->addAndLog($uid,UserLog::THREAD_ADD);
	}
	//删帖
	public function threadDel($uid){
		return $this->addAndLog($uid,UserLog::THREAD_DELETE);
	}
	//首次添加地址
	public function firstAddress($uid){
		//检查是否奖励过
		$str = UserLog::FIRST_ADDRESS;
		$typearr = explode(',',$str);
		$type    = $typearr[0];
		$r 	 = $this -> getInfo(['uid'=>$uid,'op_type'=>$type]);
		if(false === $r['status']) return $this->apiReturnErr($r['info']);
		if(empty($r['info'])){
			return $this->addAndLog($uid,$str);
		}else{
			//已奖励过
			return $this->apiReturnSuc(['err'=>[],'suc'=>[]]);
		}
	}
	//注册
	public function register($uid,$invite_uid=''){
		//检查是否奖励过
		if($invite_uid){
			//邀请码注册
			$str = UserLog::REGISTER_INVITE;
		}else{
			//非邀请码注册
			$str = UserLog::REGISTER;
		}
		$typearr = explode(',',$str);
		$type      = $typearr[0];
		$r = $this -> getInfo(['uid'=>$uid,'op_type'=>$type]);
		if(false === $r['status']) return $this->apiReturnErr($r['info']);
		if(empty($r['info'])){
			//未奖励过
			return $this->addAndLog($uid,$str);
		}else{
			//已奖励过
			return $this->apiReturnSuc(['err'=>[],'suc'=>[]]);
		}
	}
	// 更新头像
	public function firstAvatar($uid){
		//检查是否奖励过
		$str = UserLog::FIRST_AVATAR;
		$typearr = explode(',',$str);
		$type    = $typearr[0];
		$r = $this -> getInfo(['uid'=>$uid,'op_type'=>$type]);
		if(false === $r['status']) return $this->apiReturnErr($r['info']);
		if(empty($r['info'])){
			//未奖励过
			return $this->addAndLog($uid,$str);
		}else{
			//已奖励过
			return $this->apiReturnSuc(['err'=>[],'suc'=>[]]);
		}
	}

 	/*private
 	*/

	//type   score,exp
	//number 10,-10,...
	//flag   true/false
	private function getMsg($type='',$number=''){
		$str ='';
		if($type == 'score'){
			$str .= UserLog::SCORE;
		}elseif($type=='exp'){
			$str .= UserLog::EXP;
		}else{
			return '';
		}
		if($number>0)	return $str .= ' +'.$number;
		elseif($number<0) return $str .= ' '.$number;
		else return '';
	}

	//更新积分 并记录
	//更新经验 并记录
	private function addAndLog($uid,$str){
		$typearr = explode(',',$str);
		$type    = $typearr[0];
		$str   = ['err'=>[],'suc'=>[]];
		$model = new \think\model\Adv();
		$model ->startTrans();
		$score = intval($typearr[1]);
		$exp   = floatval($typearr[2]);
		$now   = time();
		if(0 !== $score){
			//update score
			if($score >0)	$result = apiCall(MemberApi::RAISE_SCORE,[$uid,$score]);
			else 	$result = apiCall(MemberApi::DECREASE_SCORE,[$uid,-$score]);
      if(!$result['status']){
      	$str['err'][] = $this->getMsg('score',$score);
      	$model ->rollback();
      }
      $note  = $this->getMsg('score',$score,true);
      $str['suc'][] = $note;
      //add record
      $map = [
				'op_type' =>$type,
				'number'  =>$score,
				'time'    =>$now,
				'uid'			=>$uid,
				'note'		=>$note,
				'num_type'=>0,
      ];
      $r = $this -> add($map);
      if(false === $r){
      	$model ->rollback();
      	return $this->apiReturnErr($this->model->getDbError());
      }
		}
		if(0 != $exp){
			//update exp
			if($exp>0) $result = apiCall(MemberExpApi::EXP_INC,[$uid,$exp]);
			else $result = apiCall(MemberExpApi::EXP_DEC,[$uid,-$exp]);
      if(!$result['status']){
      	$str['err'][] = $this->getMsg('exp',$exp);
      	$model ->rollback();
      }
      $note = $this->getMsg('exp',$exp,true);
      $str['suc'][] = $note;
      //add record
      $map = [
				'op_type' => $type,
				'number'  => $exp,
				'time'    => $now,
				'uid'			=> $uid,
				'note'		=> $note,
				'num_type'=> 1,
      ];
      $r = $this -> add($map);
      if(false === $r){
      	$model->rollback();
      	return $this->apiReturnErr($this->model->getDbError());
      }
		}
		$model ->commit();
		return $this->apiReturnSuc($str);
	}

}
